package com.sam.thread.demo;

/**
 * Created by SamZhao on 2017/5/29.
 */
public class Tickets implements Runnable {

    private int ticket = 100;

    private Object object = new Object();

    public void run() {
        while(true){
            //线程共享数据  保证安全  加入同步代码块
//            synchronized (object){//不能写匿名对象 每次进入都会新建  必须使用单例
//                method();
//            }
            method();

        }

    }

    private synchronized void method() {
        if(ticket > 0){
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+" 正在出售第 " + ticket-- + " 张票...");
        }
    }
}
